#region using

using System;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;

#endregion

/// <summary>
/// Renders the appropriate code to display a link when a [link] tag is found.
/// <example>
/// [link:netslave] will get a link with the slug "netslave" and create the anchor/link</example>
/// 
/// </summary>
[Extension("Display a link", "0.1", "BlogEngine.NET")]
public class ShowLink :RegexMatchBase
{
    private static readonly Regex _BodyRegex = new Regex(@"\[link:(\w*)(,[^\]]*)*\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);

    /// <summary>
    /// make sure the base constructs
    /// </summary>
    public ShowLink() :base()
    {
        base.Regex = _BodyRegex;
    }

    /// <summary>
    /// Handles the Page and Post Serving event to take care of the [link] keyword.
    /// </summary>
    protected override string  MatchCore(Match match)
    {
        string result = string.Empty;

        //insert the link details
        Link link = Link.GetBySlug(match.Groups[1].Value);

        if (link != null)
        {
            string innertext = link.Title;

            if (match.Groups.Count > 1 && !string.IsNullOrEmpty(match.Groups[2].Value))
            {
                innertext = match.Groups[2].Value.Remove(0,1);
            }

            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                HtmlAnchor anc = new HtmlAnchor();
                anc.Title = link.Description;
                anc.HRef = link.Website;
                anc.InnerText = innertext;
                anc.RenderControl(new HtmlTextWriter(sw));

                result = sw.ToString();
            }
        }

        return result;
    }
}
